// MemDC.cpp: implementation of the CMemDC class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "MemDC.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

CMyMemDC::CMyMemDC(CDC* pDC, const CRect* pRect) : CDC()
{
    ASSERT(pDC != NULL);

    m_dwCount = ::GetTickCount();
    
    // Some initialization
    m_pDC        = pDC;
    m_pOldBitmap = NULL;
    m_bMemDC     = !pDC->IsPrinting();
    
    // Get the rectangle to draw
    if(pRect == NULL) 
        pDC->GetClipBox(&m_rcDraw);
    else
        m_rcDraw = *pRect;
    
    if(m_bMemDC) 
    {
        m_nWidth  = m_rcDraw.Width ();
        m_nHeight = m_rcDraw.Height();
        m_nLeft   = m_rcDraw.left;
        m_nTop    = m_rcDraw.top;

        // Create a Memory DC
        CreateCompatibleDC(pDC);
        pDC->LPtoDP(&m_rcDraw);
        
        m_bmpDraw.CreateCompatibleBitmap(pDC, m_nWidth, m_nHeight);
        m_pOldBitmap = SelectObject(&m_bmpDraw);
        
        SetMapMode    (pDC->GetMapMode());        
        SetWindowExt  (pDC->GetWindowExt());
        SetViewportExt(pDC->GetViewportExt());
        
        pDC->DPtoLP (&m_rcDraw);
        SetWindowOrg(m_nLeft, m_nTop);
    }
    else
    {
        // Make a copy of the relevent parts of the current DC for printing
        m_bPrinting = pDC->m_bPrinting;
        m_hDC       = pDC->m_hDC;
        m_hAttribDC = pDC->m_hAttribDC;
    }
    
    // Fill background 
    FillSolidRect(m_rcDraw, pDC->GetBkColor());
}

CMyMemDC::~CMyMemDC()
{       
    if(m_bMemDC) 
    {
        // Copy the offscreen bitmap onto the screen.
        m_pDC->BitBlt(m_nLeft, m_nTop, m_nWidth, m_nHeight,
                      this, m_nLeft, m_nTop, SRCCOPY);
        
        //Swap back the original bitmap.
        SelectObject(m_pOldBitmap);      
    } 
    else 
    {
        // All we need to do is replace the DC with an illegal value,
        // this keeps us from accidently deleting the handles associated with
        // the CDC that was passed to the constructor.          
        m_hDC = m_hAttribDC = NULL;
    }   

//    TRACE("[MemDC Count] : %ld\n", ::GetTickCount() - m_dwCount);
}
